//
//  WithdrawVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/30.
//

import UIKit

class WithdrawVC: ZMViewController {

    //MARK:--------------------属性--------------------
    
    let walletInfo = ZMUtil.fastNilBehavior(type: MineModels.WalletInfo.self)
    
    //  0 微信 1 支付宝 2银行卡
    let currentType = ZMUtil.fastNilBehavior(type: Int.self)
    
    // 0vip商城， 普通提现1
    var type = 0
    //MARK:--------------------UI控件--------------------
    
    @IBOutlet weak var wecahtContent: UIView!
    
    @IBOutlet weak var addContent: UIView!
    
    @IBOutlet weak var inputText: UITextField!
    
    @IBOutlet weak var thirdIcon: UIImageView!
    
    @IBOutlet weak var thirdName: UILabel!
    
    @IBOutlet weak var balanceLabel: UILabel!
    
    @IBOutlet weak var withdrawBtn: UIButton!
    
    @IBOutlet weak var timeTip: UILabel!
    
    
    let loading = XMLoadingView()
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        loadInfo()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
       
        title = type == 0 ? "创客优选提现" : "提现"
//        timeTip.isHidden = type == 0
        inputText.delegate = InputMananger.shard.moneyInput
        inputText.font = Style.FONT_Alternate_Bold(32)
    }
    
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
                case .bindThirdSuccess:
                self.currentType.accept(nil)
                self.loadInfo()
                    break
                default:break
            }
        }).disposed(by: disposeBag)
        
        wecahtContent.zm.addTap(target: self, selector: #selector(thirdTap))
        
        walletInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.balanceLabel.text = "余额 ￥\(resp.balance.zm.toString(keep: 2))"
            self.timeTip.text = type == 0 ? resp.withdrawalDate : "\(resp.withdrawalDate)"
        }).disposed(by: disposeBag)
        
        Observable.combineLatest(walletInfo, inputText.rx.text.orEmpty).subscribe(onNext:{ [unowned self] resp in
            var inputOk = false
            defer {
                self.withdrawBtn.isEnabled = inputOk
                self.withdrawBtn.backgroundColor = inputOk ? Style.mainColor : Style.disableColor
            }
            
            guard let info = resp.0 else {return}
            
            if info.wxAccount.count == 0,
                info.alipayUserId.count == 0,
                info.bankNo.count == 0 {
                // 未绑定任何账号
                wecahtContent.isHidden = true
                addContent.isHidden = false
            } else {
                // 绑定了账号
                if currentType.value == nil {
                    if info.wxAccount != "" {
                        currentType.accept(0)
                    } else if info.alipayUserId != "" {
                        currentType.accept(1)
                    } else if info.bankNo != "" {
                        currentType.accept(2)
                    }
                }
                wecahtContent.isHidden = false
                addContent.isHidden = true
            }
          
            // 输入范围
            let max = info.maxMoney
            self.inputText.placeholder = "请输入(\(info.minMoney.zm.toString(keep: 2))-\(max.zm.toString(keep: 2)))"
            guard let inputMoney = Double(resp.1) else {
            return}
            inputOk = inputMoney <= max && inputMoney <= info.balance && inputMoney >= info.minMoney
        }).disposed(by: disposeBag)
        
        
        currentType.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            guard let info = self.walletInfo.value else {return}
            if resp == 0 {
                self.thirdName.text = info.wxName
                self.thirdIcon.image = UIImage.init(named: "team_wechat")
            } else if resp == 1 {
                self.thirdName.text = "支付宝账户"
                self.thirdIcon.image = UIImage.init(named: "pay_tool_alipay")
            } else if resp == 2 {
                let bankNo = self.walletInfo.value!.bankNo
                self.thirdName.text = "\(self.walletInfo.value!.bankName)(**\(bankNo.zm.substring(from: bankNo.count - 4)))"
                self.thirdIcon.image = UIImage.init(named: "pay_tool_bank")
            }
        }).disposed(by: disposeBag)
    }
        
    @objc func thirdTap() {
        guard let info = walletInfo.value else {return}
        let v = ZMUtil.loadNibViewFullScreen(nibName: ChoosePayToolView.self)

        v.wechatContent.isHidden = info.wxAccount == ""
        v.aliContent.isHidden = info.alipayUserId == ""
        v.cardContent.isHidden = info.bankNo == ""
        v.addContent.isHidden = info.wxAccount == "" && info.alipayUserId == "" && info.bankNo == ""
        
        if info.bankNo.count > 0 {
            v.bankLabel.text = "\(info.bankName)(**\(info.bankNo.zm.substring(from: info.bankNo.count - 4)))"
        }
        
        v.wxLabel.text = info.wxName
        v.aliLabel.text = info.alipayName
        // 自动选中第一个
        if info.wxAccount != "" {
            v.onSelect(v.buttonArray.first(where: {$0.tag == 100})!)
        } else if info.alipayUserId != "" {
            v.onSelect(v.buttonArray.first(where: {$0.tag == 101})!)
        } else if info.bankNo != "" {
            v.onSelect(v.buttonArray.first(where: {$0.tag == 102})!)
        }
        
        v.addButton.rx.tap.subscribe(onNext:{ [unowned self, weak v] resp in
            v?.removeFromSuperview()
            router.push("xm://main/Mine/third_account")
        }).disposed(by: disposeBag)
        
        v.confirmBlock = { [weak self, weak v] in
            guard let self = self, let v = v else {return}
            self.currentType.accept(v.index)
        }
        APPWindow?.addSubview(v)
    }
    
    func loadInfo() {
        let api : ZMApiProvider = type == 0 ? VIPMallAPI.walletInfo([:]) : MineAPI.walletInfo([:])
        api.rxRequest(type: MineModels.WalletInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.walletInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    @IBAction func onAddAccount(_ sender: Any) {
        router.push("xm://main/Mine/third_account")
    }
    
    @IBAction func onAll(_ sender: Any) {
        guard let info = walletInfo.value else {return}
        self.inputText.text = info.balance.zm.toString(keep: 2)
        self.inputText.sendActions(for: .valueChanged)
    }
    
    @IBAction func onWithdraw(_ sender: Any) {
        view.endEditing(true)
        guard let info = walletInfo.value else {return}
        var money = NSDecimalNumber.init(string: inputText.text!)
        if !ZMAppShareData.share.safeUserInfo.isTradeOk {
            // 判断是否设置交易密码
            ZMAlertView.show(content: "还未设置交易密码", left: "关闭", right: "马上去设置") {
                
            } onRight: {
                let cls = Swift.type(of: self)
                MineService.shared.tradeSuccessToVC = cls
                let vc = TradeFroget()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            return
        }
        
        // 判断有没有绑卡
        guard let withdrawType = self.currentType.value else {
            ZMToast.showToast(title: "请绑定提现账号")
            return
        }
        
        let typeStr = mapTypeToString(type: withdrawType)
        
        let h = ZMUtil.DecimalNumberHandler(roundingMode: .bankers, scale: 2)
        var serviceFee = money.multiplying(by: NSDecimalNumber.init(value: info.feeRatio)).dividing(by: NSDecimalNumber.init(value: 100)).rounding(accordingToBehavior: h)
        if type == 0 {
            // 创客
            if serviceFee.adding(money).compare(NSDecimalNumber.init(value: info.balance)) == .orderedDescending {
                // 大于
    //            max = money / (1+ratio)
                let allMoney = NSDecimalNumber.init(value: info.balance)
                let ratio = NSDecimalNumber.init(value: info.feeRatio).dividing(by: NSDecimalNumber.init(value: 100))
                money = allMoney.dividing(by: ratio.adding(NSDecimalNumber.init(value: 1))).rounding(accordingToBehavior: h)
                serviceFee = money.multiplying(by: ratio).rounding(accordingToBehavior: h)
            }
        } else {
            serviceFee = serviceFee.multiplying(by: NSDecimalNumber.init(value: info.moneyToIntegral))
        }
        
        let feeTitle = type == 0 ? "服务费：￥\(serviceFee.stringValue)" : "服务费：\(serviceFee.stringValue)积分"
        
        // 发起提现请求
        CommonService.shared.showPsdInput(money: money.stringValue, left : feeTitle, right : "费率：\(info.feeRatio.zm.xmToString(keep: 2, mode: .plain))%") { psd, close in
            let pa = [
                "tradePwd" : psd,
                "extractType" : typeStr,
                "money" : money.stringValue,
                "type" : 1 - self.type
            ] as [String : Any]
            ZMToast.showActivity()
            let api : ZMApiProvider = MineAPI.withdrawApply(pa)
            api.rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.loadInfo()
                self.inputText.text = ""
                self.inputText.sendActions(for: .valueChanged)
                close(true)
                ZMToast.showToast(title: "提现申请已提交")
            }, onError: { _ in
                close(true)
            }).disposed(by: self.disposeBag)
        }
    }
    
    
    // 提现方式| alipay=支付宝,bank=银行卡,weixin=微信
    func mapTypeToString(type : Int) -> String {
        if type == 0 {
            return "weixin"
        } else if type == 1 {
            return "alipay"
        } else if type == 2 {
            return "bank"
        }
        return ""
    }
    
    //MARK:--------------------delegate--------------------

}
